/*
 * user.c
 *
 *  Created on: Mar 4, 2012
 *      Author: Administrator
 */
#include "user.h"
#include "utils.h"
#include "xmppconnect.h"
static struct user_manager *xmpp_2_sip_user_manager = NULL;

int xmpp_2_sip_set_user_manager(struct user_manager *user_manager)
{
	xmpp_2_sip_user_manager = user_manager;
	return 0;
};
int xmpp_2_sip_find_user_by_sip_user_name(char *sip_username,struct _sip_user_ **user)
{
	if(!xmpp_2_sip_user_manager)
	{
		LogD("xmpp_2_sip_user_manager not initliazed.");
		return 1;
	}
	return xmpp_2_sip_user_manager->find_user_by_sip_user_name(sip_username,user);
}

int remove_deleted_users(sip_user_t **users)
{
	sip_user_t *user,*tmp_user = NULL,*delete_user = NULL;
	xmpp_connection_t *xmpp_connection = NULL;
	if(*users)
	{
		tmp_user = *users;
		while(tmp_user->next)
		{
			if(!tmp_user->next->delete_flag)
			{
				delete_user = tmp_user->next;
				tmp_user->next = tmp_user->next->next;
				if(!sipxmpp_find_connection_by_sip_username(delete_user->xmpp_username,&xmpp_connection) && xmpp_connection)
				{
					sipxmpp_destroy_xmpp_connection(xmpp_connection);
				}
				chkndfree(delete_user);
			}
			else
				tmp_user = tmp_user->next;
		}
		//we did not check delete_flag of sip_users in previous loop.
		if(!(*users)->delete_flag)
		{
			delete_user = *users;
			*users = (*users)->next;
			if(!sipxmpp_find_connection_by_sip_username(delete_user->xmpp_username,&xmpp_connection) && xmpp_connection)
			{
				sipxmpp_destroy_xmpp_connection(xmpp_connection);
			}
			chkndfree(delete_user);
		}

		//reset flag
		tmp_user = *users;
		while(tmp_user)
		{
			tmp_user->delete_flag = 0;
			tmp_user = tmp_user->next;
		}
	}
	return S_OK;
}
